package com.youths.controller;

import com.youths.domain.LabelConsumer;
import com.youths.response.Result;
import com.youths.service.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 * User: KingRainGrey
 * Date: 2020/6/22
 */
@Controller
@RequestMapping("/")
public class RegisterController {
    @Autowired
    RegisterService registerService;

    @GetMapping(value = "register")
    public String register() {
        return "register";
    }

    @PostMapping(value = "consumerRegister")
    public String ConsumerLogin(@RequestParam("phone") String phone,
                                @RequestParam("consumerName") String consumerName,
                                @RequestParam("password") String password,
                                @RequestParam("checkPassword") String checkPassword,
                                Model model) {
        try {
            String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}$";
            if (Pattern.matches(regex,phone)) {
                if (!registerService.check(phone)) {
                    if (password.equals(checkPassword)) {
                        if (password.length() >= 8) {
                            //kind0 普通用户 kind1 专家
                            if (registerService.consumerRegister(phone, password, consumerName,0, 1) > 0) {
                                model.addAttribute("msg", "注册成功");
                            }else {
                                model.addAttribute("msg", "注册失败");
                            }
                        }else {
                            model.addAttribute("msg", "密码太短");
                        }
                    }else {
                        model.addAttribute("msg", "两次密码不一致");
                    }
                }else {
                    model.addAttribute("msg", "手机号已经注册");
                }
            }else {
                model.addAttribute("msg", "手机号格式错误");
            }
        } catch (Exception e) {
            model.addAttribute("msg", e.getStackTrace());
            e.printStackTrace();
        }

        return "register";
    }

    @PostMapping("/back/createAdmin")
    @ResponseBody
    public Result createAdmin(@RequestParam("phone") String phone,
                              @RequestParam("name") String name){
        return Result.success(registerService.createAdmin(phone,name));
    }

}
